package com.tledu.spring.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tledu.spring.core.vo.BasicVo;
import com.tledu.spring.dao.RoleMapper;
import com.tledu.spring.domain.Role;
import com.tledu.spring.service.IRoleService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author Lsj
 * @version 1.0
 * @date 2021/7/2 21:51
 */
@Service
@AllArgsConstructor
public class RoleServiceImpl implements IRoleService {
    private final RoleMapper roleMapper;


    /**
     * 查询
     *
     * @param page  第几页
     * @param limit 几条数据
     * @return 等待转换json的数据
     */
    @Override
    public BasicVo<Role> selectByAll(Integer page, Integer limit) {
        BasicVo basicVo = new BasicVo();
        basicVo.setCode(0);
        basicVo.setMsg("");
        IPage<Role> roleIPage = new Page<>(page,limit);
        IPage<Role> result = roleMapper.selectPage(roleIPage,null);
        basicVo.setCount(result.getTotal());
        // 获得记录
        List<Role> roleList = result.getRecords();
        List<Role> roleVoList = new ArrayList<>();
        for (Role role:roleList){
            roleVoList.add(role);
        }
        basicVo.setData(roleVoList);
        return basicVo;
    }

    /**
     * 插入数据
     *
     * @param role
     * @return
     */
    @Override
    public int insertSelective(Role role) {
        return roleMapper.insert(role);
    }

    /**
     * 查看role全部数据
     *
     * @param role role
     * @return 全部数据
     */
    @Override
    public List<Role> selectByAll(Role role) {
        return roleMapper.selectByAll(role);
    }

    /**
     * 更新
     *
     * @param updated
     * @param r_id
     * @return
     */
    @Override
    public int updateByR_id(Role updated, Integer r_id) {
        return roleMapper.updateByR_id(updated,r_id);
    }


    /**
     * 根据id查询
     *
     * @param rId
     * @return
     */
    @Override
    public Role selectById(Integer rId) {
        return roleMapper.selectAllByR_id(rId).get(0);
    }

    /**
     * 删除
     *
     * @param rid
     * @return
     */
    @Override
    public int deleteByR_id(String rid) {
        List<String> item = Arrays.asList(StringUtils.split(rid,","));
        List<Integer> intItem = new ArrayList<>();
        for (String term:
             item) {
            intItem.add(Integer.parseInt(term));
        }
        for (Integer r_id:intItem){
            if (r_id!=null){
                roleMapper.deleteByR_id(r_id);
            }
        }
        return 1;
    }

    /**
     * 根据name查role
     *
     * @param r_name
     * @return
     */
    @Override
    public Role selectAllByR_name(String r_name) {
        return roleMapper.selectAllByR_name(r_name);
    }
}
